package com.yxt.qmgf.userinfo.ctrl;

import cn.hutool.extra.spring.SpringUtil;
import com.yxt.qmgf.common.view.CdzAlert;
import com.yxt.qmgf.userinfo.dao.UserInfoDao;
import com.yxt.qmgf.userinfo.service.UserInfoService;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import com.yxt.qmgf.common.IPubCost;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

@FXMLController
public class UserInfoController implements Initializable {

    @FXML
    private TextField tf_username;
    @FXML
    private TextField tf_name;
    @FXML
    private ComboBox<String> cb_sex;//性别
    @FXML
    private ComboBox<String> cb_code;//管理员（0：否，1：是）
    @FXML
    private TextField tf_score;//游戏积分
    @FXML
    private TextField tf_email;
    @FXML
    private TextField tf_TelNumber;
    @FXML
    private TextField tf_title;//头像
    @FXML
    private TextField tf_game;//游戏
    @FXML
    private TextField tf_uid;

    @FXML
    private Label lbl_personal_info;

    @FXML
    private TableView<UserInfoVO> tbl_accounts;
    @FXML
    private TableColumn<UserInfoVO, String> col_username;
    @FXML
    private TableColumn<UserInfoVO, String> col_name;
    @FXML
    private TableColumn<UserInfoVO, String> col_sex;
    @FXML
    private TableColumn<UserInfoVO, String> col_code;
    @FXML
    private TableColumn<UserInfoVO, String> col_score;
    @FXML
    private TableColumn<UserInfoVO, String> col_email;
    @FXML
    private TableColumn<UserInfoVO, String> col_telNumber;
    @FXML
    private TableColumn<UserInfoVO, Void> col_operation;

    private UserInfoVO vo = null;

    private Stage stage;
    @FXML
    ScrollPane scrollPane;

    public UserInfoController() {
        super();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //下拉条填充内容
        cb_sex.getItems().addAll(IPubCost.sexs);
        cb_code.getItems().addAll(IPubCost.codes);

        // 初始化表格列
        col_username.setCellValueFactory(new PropertyValueFactory<>("username"));
        col_name.setCellValueFactory(new PropertyValueFactory<>("name"));
        col_sex.setCellValueFactory(new PropertyValueFactory<>("sex"));
        col_code.setCellValueFactory(new PropertyValueFactory<>("code"));
        col_score.setCellValueFactory(new PropertyValueFactory<>("score"));
        col_email.setCellValueFactory(new PropertyValueFactory<>("email"));
        col_telNumber.setCellValueFactory(new PropertyValueFactory<>("telNumber"));

        // 设置操作列的单元格工厂
        col_operation.setCellFactory(param -> new TableCell<UserInfoVO, Void>() {
            private final Button viewButton = new Button("查看");
            private final Button editButton = new Button("修改");
            private final Button deleteButton = new Button("删除");

            {
                viewButton.setOnAction(event -> {
                    UserInfoVO selectedAccount = getTableView().getItems().get(getIndex());
                    viewAccount(selectedAccount);
                });
                editButton.setOnAction(event -> {
                    UserInfoVO selectedAccount = getTableView().getItems().get(getIndex());
                    editAccount(selectedAccount);
                });
                deleteButton.setOnAction(event -> {
                    UserInfoVO selectedAccount = getTableView().getItems().get(getIndex());
                    deleteAccount(selectedAccount);
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    HBox hbox = new HBox(viewButton, editButton, deleteButton);
                    hbox.setSpacing(5);
                    setGraphic(hbox);
                }
            }
        });
    }

    public void setOff(UserInfoVO vo) {
        this.vo = vo;
        if (vo != null) {
            tf_username.setText(vo.getUsername() == null? "" : vo.getUsername());
            tf_name.setText(vo.getName());
            cb_sex.setValue(vo.getSex() == null? "" : vo.getSex());
            if ("0".equals(vo.getCode())) {
                cb_code.setValue("玩家");
            } else if ("1".equals(vo.getCode())) {
                cb_code.setValue("管理员");
                // 管理员信息标红
                lbl_personal_info.setStyle("-fx-text-fill: red; -fx-font-size: 20px; -fx-font-weight: bold;");
                // 显示账号信息列表
                showAllAccounts();
            } else {
                // 处理其他可能的值，或者设置一个默认值
                cb_code.setValue("未知");
            }
            tf_score.setText(vo.getScore() == null? "0" : vo.getScore());
            tf_email.setText(vo.getEmail() == null? "" : vo.getEmail());
            tf_TelNumber.setText(vo.getTelNumber() == null? "" : vo.getTelNumber());
        }
    }

    private void showAllAccounts() {
        // 获取所有账号信息
        List<UserInfoVO> accounts = SpringUtil.getBean(UserInfoDao.class).selectList(null);
        ObservableList<UserInfoVO> accountList = FXCollections.observableArrayList(accounts);
        tbl_accounts.setItems(accountList);
        tbl_accounts.setVisible(true);
    }

    @FXML
    private void commit() {
        UserInfoVO uvo = vo; // 确保 vo 是已经初始化的 UserInfoVO 对象
        uvo.setCode(cb_code.getValue());
        uvo.setUsername(tf_username.getText());
        uvo.setName(tf_name.getText());
        uvo.setSex(cb_sex.getValue());
        uvo.setScore(tf_score.getText());
        uvo.setTelNumber(tf_TelNumber.getText()); // 注意方法名与字段名的大小写一致性
        uvo.setEmail(tf_email.getText());

        // 如果 title 是可选的，并且您想将其设置为 null，那么这行代码是可以的
        // 否则，您应该为它提供一个有效的值或者保持它的当前值不变
        uvo.setTitle("null");
        uvo.setGame("10");

        // 假设 SpringUtil.getBean(UserInfoService.class) 能够正确获取到 UserInfoService 的实例
        SpringUtil.getBean(UserInfoDao.class).UpdateByVo(uvo);
        //  SpringUtil.getBean(UserInfoService.class).updateById(uvo);

        // 显示保存成功的提示信息
        new CdzAlert(Alert.AlertType.INFORMATION, "保存成功").show();
    }

    private void viewAccount(UserInfoVO account) {
        StringBuilder info = new StringBuilder();
        info.append("账号: ").append(account.getUsername()).append("\n");
        info.append("用户名: ").append(account.getName()).append("\n");
        info.append("性别: ").append(account.getSex()).append("\n");
        info.append("身份: ").append(account.getCode()).append("\n");
        info.append("积分: ").append(account.getScore()).append("\n");
        info.append("邮件: ").append(account.getEmail()).append("\n");
        info.append("电话: ").append(account.getTelNumber()).append("\n");

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("账号信息");
        alert.setHeaderText(null);
        alert.setContentText(info.toString());
        alert.showAndWait();
    }

    private void editAccount(UserInfoVO account) {
        tf_username.setText(account.getUsername());
        tf_name.setText(account.getName());
        cb_sex.setValue(account.getSex());
        cb_code.setValue(account.getCode());
        tf_score.setText(account.getScore());
        tf_email.setText(account.getEmail());
        tf_TelNumber.setText(account.getTelNumber());
        // 可以在这里添加逻辑，例如设置保存按钮的点击事件，
        // 点击后调用UserInfoDao的UpdateByVo方法保存修改
        // 示例：
         Button saveButton = new Button("保存修改");
         saveButton.setOnAction(event -> {
             UserInfoVO updatedAccount = new UserInfoVO();
             updatedAccount.setUsername(tf_username.getText());
             updatedAccount.setName(tf_name.getText());
             updatedAccount.setSex(cb_sex.getValue());
             updatedAccount.setCode(cb_code.getValue());
             updatedAccount.setScore(tf_score.getText());
             updatedAccount.setEmail(tf_email.getText());
             updatedAccount.setTelNumber(tf_TelNumber.getText());
             SpringUtil.getBean(UserInfoDao.class).UpdateByVo(updatedAccount);
             new CdzAlert(Alert.AlertType.INFORMATION, "修改成功").show();
         });
        // 这里只是简单示例，实际可能需要更复杂的布局和逻辑，
        // 比如在新窗口中展示输入框等
    }

    private void deleteAccount(UserInfoVO account) {
        // 实现删除账号信息的逻辑
        SpringUtil.getBean(UserInfoDao.class).DeleteByUid(account.getUid());
        showAllAccounts();
    }
}